module.exports = {
	/**
	 * 添加单条数据
	 * @url client/history/pub/add 前端调用的url参数地址
	 * data 请求参数 说明
	 * res 返回参数说明
	 * @params {Number} code 错误码，0表示成功
	 * @params {String} msg 详细信息
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: 'ok'
		};
		// 业务逻辑开始-----------------------------------------------------------
		// 获取前端传过来的参数
		let {
			user_id,
			nickname,
			tv_name,
			is_follow,
			tv_id,
			series,
			series_id,
			tv_image,
			_add_time,
			_add_time_str,
			tfid,
			invite_code,
			middleman_id,
		} = data;
		// 参数验证开始


		// 参数验证结束
		let dbName = "a_history"; // 表名
		console.log("user_id=", user_id);
		console.log("tv_id=", tv_id);
		//先查一下数据库，看之前是否记录过该剧的历史记录，history.affectedDocs是已存在数量
		const history = await db.collection('a_history').where({
			tv_id: tv_id,
			user_id: user_id
		}).get()

		console.log("history=", history);
		if (history.data.length > 0) {
			var nowtime = new Date().getTime()
			db.collection('a_history').where({
				tv_id: tv_id,
				user_id: user_id
			}).update({
				series: series,
				series_id: series_id,
				_add_time: nowtime
			})

			//更新追剧表
			db.collection('a_follow_tv').where({
				tv_id: tv_id,
				user_id: user_id
			}).update({
				series: series,
				series_id: series_id,
				_add_time: nowtime
			})
			res.status = "修改历史记录成功"
		} else {
			// 执行 数据库add 命令
			res.id = await vk.baseDao.add({
				dbName,
				dataJson: {
					user_id,
					nickname,
					tv_name,
					is_follow,
					tv_id,
					series,
					series_id,
					tfid,
					invite_code,
					middleman_id,
					tv_image,
					_add_time,
					_add_time_str
				}
			});
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
